import { useState, FormEvent, ChangeEvent } from "react";
import axios, { AxiosError } from "axios";
import { useNavigate } from "react-router-dom";

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:5001";

// Define an interface for the API error response
interface ApiErrorData {
  error?: string;
}

const CreateDataset = () => {
  const [name, setName] = useState<string>("");
  const [description, setDescription] = useState<string>("");
  const [indexingTechnique, setIndexingTechnique] = useState<string>("high_quality"); // Default value
  const [error, setError] = useState<string | null>(null); // Explicitly type error state
  const [loading, setLoading] = useState<boolean>(false);
  const navigate = useNavigate();

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);
    setError(null);

    if (!name.trim()) {
      setError("知识库名称不能为空");
      setLoading(false);
      return;
    }

    try {
      const payload = {
        name,
        description,
        indexing_technique: indexingTechnique,
        // Add other fields like embedding_model_provider, embedding_model_name if needed
      };
      const response = await axios.post(`${API_BASE_URL}/datasets`, payload);
      console.log("Dataset created:", response.data);
      // Navigate to the datasets list or the new dataset"s page
      navigate("/datasets");
    } catch (err) {
      console.error("Error creating dataset:", err);
      const axiosError = err as AxiosError<ApiErrorData>; // Type assertion
      if (axiosError.response) {
        setError(
          `创建失败: ${axiosError.response.status} - ${axiosError.response.data?.error || "服务器错误"}`
        );
      } else if (axiosError.request) {
        setError("服务器无响应，请检查后端服务是否运行。");
      } else {
        setError("创建请求时发生错误。");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h2>创建新知识库</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="name">名称:</label>
          <input
            type="text"
            id="name"
            value={name}
            onChange={(e: ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
            required
          />
        </div>
        <div>
          <label htmlFor="description">描述:</label>
          <textarea
            id="description"
            value={description}
            onChange={(e: ChangeEvent<HTMLTextAreaElement>) => setDescription(e.target.value)}
          />
        </div>
        <div>
          <label htmlFor="indexingTechnique">索引技术:</label>
          <select
            id="indexingTechnique"
            value={indexingTechnique}
            onChange={(e: ChangeEvent<HTMLSelectElement>) => setIndexingTechnique(e.target.value)}
          >
            <option value="high_quality">高质量</option>
            <option value="economy">经济</option>
          </select>
        </div>
        {/* Add more fields as needed, e.g., for embedding model selection */}
        <button type="submit" disabled={loading}>
          {loading ? "正在创建..." : "创建知识库"}
        </button>
        {error && <p style={{ color: "red" }}>{error}</p>}
      </form>
    </div>
  );
};

export default CreateDataset;

